<template>
  <view class="status_card_main">
    <view v-for="(data, index) in status.card_data" :key="index">
      <view v-if="status.loading[index]">Loading...</view>
      <view v-else>
        <DataCard :data="data" :time="currentTime"/>
      </view>
    </view>
  </view>
</template>

<style scoped>
.status_card_main
{
  display: flex;
  width: 100%;
  height: 160px;
  align-items: center;
  justify-content: space-around;
  max-height: 160px;
}
</style>
<script setup>

import {reactive, onMounted, ref} from 'vue';
import DataCard from './home_items/DataCard.vue';
import {ElMessage} from "element-plus";
import router from "@/router";

const cardData = ref({
  title: '',
  number: 0,
  percentage: 0,
  chartData: {
    labels: [],
    data: []
  }
});

const currentTime = ref(new Date().toISOString());
/*const loading = ref([]);*/

const status = reactive({
  url: [
    'https://movie.cpb2013.top/admin/status.php?mode=get_account_online_status',
    'https://movie.cpb2013.top/admin/status.php?mode=get_account_rank_status',
    'https://movie.cpb2013.top/admin/status.php?mode=get_upload_video_status',
    'https://movie.cpb2013.top/admin/status.php?mode=get_video_comment_status',
  ],
  loading: [true, true, true, true],
  card_data: [cardData,cardData,cardData,cardData]
});

const fetchData = async (ID) => {
  const formData = new FormData();
  // 在此添加需要发送的表单数据
  // formData.append('key', 'value');
  formData.append('key', localStorage.getItem('key'));
  try {
    const response = await fetch(status.url[ID], {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
      },
      body: formData,
    });

    if (!response.ok) {
      throw new Error('Network response was not ok');
    }

    const data = await response.json();
    // 将获取到的数据存入 cardData 中
    if(data['status'] === 'success')
    {
      Object.assign(status.card_data[ID], data['data']);
      console.log(status.card_data[ID]);
      status.loading[ID] = false;
    }
    else if (data['status'] === 'danger') {
      localStorage.removeItem('key');
      ElMessage.error(data['msg']);
      await router.push('/login'); // Use router to navigate to the login page
    }
  } catch (error) {
    console.error('There was a problem with the fetch operation:', error);
  }
/*  finally {
    status.loading[ID] = false;
  }*/
};

onMounted(() => {
  fetchData(0);
  fetchData(1);
  fetchData(2);
  fetchData(3);
});
</script>
